﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Henke.DevUI.Policy.MVVM;
using Henke.DevUI.Policy.MVVM.DevUISpecific;

namespace Henke.DevUI.Policy.Common
{
    /// <summary>
    /// Helper to load assemblies for policytesting
    /// </summary>
    public class All
    {
        private static IMVVMDialect _dialect = new DevUIDialect();
        private static Assembly _calling;

        public static IList<Assembly> TargetAssemblies { get; set; }

        public static  IMVVMDialect Dialect
        {
            get { return _dialect; }
            set { _dialect = value; }
        }

        public static IEnumerable<IPolicyTarget> ViewModels
        {
            get
            {   
                    CheckLoad(Assembly.GetCallingAssembly());
                    return new PolicyTargetRepo(TargetAssemblies).All(_dialect.DefinitionOfAViewModel).ToList();           
            }
        }

        private static void CheckLoad(Assembly callingAssembly)
        {
            _calling = callingAssembly;
            if (TargetAssemblies == null) LoadAllReferencedAssembliesWithsameNameSpace();
        }
 
        private static void LoadAllReferencedAssembliesWithsameNameSpace()
        {
            var referencedAssemblies = _calling.GetReferencedAssemblies();

            var seachName = Remove.LastDotBefore("Policy", _calling.FullName);

            var assembleysToBeLoaded = from refAssembly in referencedAssemblies
                                       where refAssembly.Name.Contains(seachName)
                                       select Assembly.Load(refAssembly.FullName);
            TargetAssemblies = assembleysToBeLoaded.ToList();
        }
       
    }
}
